package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationDao relationDao;
    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //1.保存attr的基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        //2.保存关联关系
        //表明这个是基本属性
        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
            && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            //从attrVo中获取属性分组id
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        //.eq("attr_type","base".equalsIgnoreCase(type)? 1 : 0)
        //表示，通过判断当前的属性是否为base，是则是基本属性，否则是销售属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(type) ?
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        //判断条件-传入值id是否为0
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");
        //检索条件不等于空时
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                //检索条件拼接  attr_id or attr_name
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        //把这个attrRespVos设置到page中返回，补充冗余字段
        List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
            //设置当前RespVo的属性
            AttrRespVo attrRespVo = new AttrRespVo();

            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //1.设置分类和分组的名字
            //如果传入的类型是base，才需要放入关联表
            if("base".equalsIgnoreCase(type)){
                //第一步，需要先从关联表中，查取分组的id
                AttrAttrgroupRelationEntity attrAttrgroupRelation = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrEntity.getAttrId()));
                if (attrAttrgroupRelation != null && attrAttrgroupRelation.getAttrGroupId() != null) {
                    //第二步，通过分组的id，在分组表中查取分组的名字
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                    //第三步，放入这个分组名字
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            //从categoryDao中查取分类信息
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        //使用最新的处理集  attrRespVos  不在使用原来vo的字段，新加入了catelogName、groupName
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    @Cacheable(value = "attr", key = "'attrInfo'+#root.args[0]")
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        //把基本数据放入到attrRespVo中
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        //判断是否需要添加分组信息
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //需要放入两个属性，一个是分组id，另一个是分类的路径
            //1.需要先通过关联表，查出分组和分类的关联信息
            AttrAttrgroupRelationEntity attrAttrgroupRelation = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            //需要进行非空判断
            if (attrAttrgroupRelation != null) {
                //2.通过关联表，查出它对应的分组id,放入到attrRespVo中
                attrRespVo.setAttrGroupId(attrAttrgroupRelation.getAttrGroupId());
                //3.通过关联表中的分组id，查出它对应的分组信息
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                //4.将分组信息对应名字放入到attrRespVo中，需判断分组信息是否为空
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //设置分类信息
        //5.通过关联表，把他分类的信息依次递归返回
        Long catelogId = attrEntity.getCatelogId();
        //注入categoryService，有方法可以查询分类路径
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        //注入这个分类信息
        attrRespVo.setCatelogPath(catelogPath);
        //获取分类名，注入属性
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        //非空判断
        if(categoryEntity!=null){
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }
    @Transactional//事务控制
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //把基本的页面信息放入到attrEntity中
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        //判断是否需要添加分组信息
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //1.修改分组关联
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));
            //更新关联关系
            AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
            //需要更新分组id和分类id关联表
            attrAttrgroupRelation.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelation.setAttrId(attr.getAttrId());

            //count大于0，表示这是修改操作
            if (count > 0) {
                relationDao.update(attrAttrgroupRelation,
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));

            } else {
                //新增操作
                relationDao.insert(attrAttrgroupRelation);
            }
        }
    }

    /**
     * 根据分组id查找关联的所有基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        //从关联表中查询与分组id所匹配的所有分类id，
        // 然后根据这些分类id查询对应的分类信息
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));
        //通过这个关联列表，查取所有的分类信息的id集合
        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }


        //通过这个查询出的ids集合，使用AttrService的listByIds方法，一次性获取所有的分类信息
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);

        //返回所有信息
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrGroupRelationVo> relationVos = Arrays.asList(vos);
        List<AttrAttrgroupRelationEntity> entities = relationVos.stream().map((relationVo) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(relationVo, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        //根据attrId，attrGroupId批量删除关联关系
        relationDao.deleteBatchRelation(entities);
    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1.当前分组只能关联自己所属的分类的所有属性
        //通过分组id查出当前分组信息
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //从分组信息获取到分类的信息
        Long catelogId = attrGroupEntity.getCatelogId();//分类id
        Long[] path = attrGroupEntity.getCatelogPath();//分类的路径
        //2.当前分组只能关联别的分组没有引用的属性
        //2.1 当前分类下的其他分组  通过分类id进行查询相同分类的不同分组的信息
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
//                .ne("attr_group_id",attrgroupId));
        //获取分类id相等的其他分组的分组id信息，封装成list
        List<Long> collect = groupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //2.2 这些分类关联的属性
        //通过分组id获取关联表的信息
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", collect));
        //通过关联表的信息，获取分组关联的属性
        List<Long> attrIds = groupId.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //2.3 从当前分类的所有属性中移除这些属性，
        //通过当前的服务方法中，查询所有在同一分类下，但是不属于同一商品属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
//                .notIn("attr_id", attrIds);
        //判断notIn是否为空
        if(attrIds!=null && attrIds.size() > 0) {
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");

        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key)
                        .or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),
                wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        return this.baseMapper.selectSearchAttrIds(attrIds);
    }

}